var root_domain = "https://www.baidu.com/";
let init_excluded_cartoon_sites = [
    'haokan.baidu.com',
    'bilibili.com',
    'v.qq.com',
    'iqiyi.com',
    'zlyk.com',
    'v.youku.com',
    'acfun.cn'
];

let excluded_cartoon_sites = [];

var tDetectionInterval = 15;  // Minimum 15 seconds  We set to 120
var bool_open_detection = true;  // 当active后才再次激活，如果resetToHome()执行后，就不必检查idle了
// 开启log 输出调试
var bool_log_echo = true;
const log_echo = (...val) => {
    if (bool_log_echo) {
        console.log.apply(console, val);
    }
};

chrome.runtime.onInstalled.addListener(
    function(details) {
        // 加载时先检查storage是否存有store_id，没有就默认设为138 Milton，有的话，就再set 一次
        chrome.storage.sync.get({'excluded_cartoon_sites': init_excluded_cartoon_sites}, function(data) {
            excluded_cartoon_sites = data.excluded_cartoon_sites;
            log_echo("OnInstalled, " + excluded_cartoon_sites);
        });
        chrome.storage.sync.set({'focus_tab_id': []}, function() {
            log_echo("Clear focus_tab_id ");
        });

        if (details.reason == 'install') {
            log_echo("Install: " + now_date());
        }

        if (details.reason == 'update') {
            log_echo("Update: " + now_date());
        }

        chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
            chrome.declarativeContent.onPageChanged.addRules([{
                conditions: [new chrome.declarativeContent.PageStateMatcher({
                })],
                actions: [new chrome.declarativeContent.ShowPageAction()]
            }]);
        });
    }
);
// 设置空闲检查间隔时间 second
chrome.idle.setDetectionInterval(tDetectionInterval);

// 监测idle状态，就弹出提示窗口
chrome.idle.onStateChanged.addListener(function(state) {
    if (state === "idle" && bool_open_detection) {
        log_echo("Change to idle.");
        // 检查当前 Tab url是否是Cartoon 网站
        chrome.windows.getAll(function (win_objs) {
            log_echo(win_objs);
            for (let k in win_objs) {
                chrome.tabs.query(
                    {
                        active: true,
                        windowId: win_objs[k].id
                    },
                    function(tabs) {
                        if (typeof(tabs[0]) !== 'undefined') {
                            for (let key in excluded_cartoon_sites) {
                                if (tabs[0].url.indexOf(excluded_cartoon_sites[key]) >= 0) {
                                    show_comfirm_panel(tabs[0].id);
                                }
                            }
                        } else {
                            log_echo("Can not find Sub tabs[0]");
                        }
                    }
                );
            }

        });

    }
    
    if (state === "active") {
        // bool_open_detection = true;
        log_echo("Change to active.");
    }
});

// 监听来自tab content script 传来的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if (request.reset_tab_id > 0) {
        // 处理超时无人响应,回到local store home page, close idle status detection until next user arrival
        resetToHome(request.reset_tab_id);
        // bool_open_detection = false;
    }
    sendResponse({"success": 1}); //做出回应
});


// Logout & Back to the current store home page
function resetToHome(reset_tab_id) {
    log_echo("Reset to home page.");
    chrome.tabs.executeScript(
        reset_tab_id,
        {code: 'window.location.replace("' + root_domain + '")'}
    );
}

// remove tab
function remove_tab(op_tab) {
    if (op_tab.pinned) {
        // 固定标签页面不能remove 只能return index page
        chrome.tabs.executeScript(
            op_tab.id,
            {code: 'window.location.replace("' + root_domain + '")'}
        );
    } else {
        chrome.tabs.remove(op_tab.id);
    }
}

function now_date() {
    var myDate = new Date;
    var year = myDate.getFullYear();
    var mon = myDate.getMonth() + 1;
    var date = myDate.getDate();
    var h = myDate.getHours();
    var m = myDate.getMinutes();
    var s = myDate.getSeconds();
    return date + "/" + mon + "/" + year + " " + h + ":" + m + ":" + s;
}

// 在当前tab page 弹出提示窗口
function show_comfirm_panel(op_tab_id){
    chrome.tabs.insertCSS(
        op_tab_id,
        {file: "assets/css/style.css", runAt: "document_end"},
        function () {
            chrome.tabs.executeScript(
                op_tab_id,
                {file: "assets/js/jquery.min.js", runAt: "document_end"},
                function () {
                    chrome.tabs.executeScript(
                        op_tab_id,
                        {code: "var tab_id = " + op_tab_id + ";" , runAt: "document_end"}
                    );
                    chrome.tabs.executeScript(
                        op_tab_id,
                        {file: "assets/js/modal.js", runAt: "document_end"}
                    );
                }
            );
        }
    );

}

/**
 * Close all cartoon websites
 https://haokan.baidu.com/
 https://v.qq.com/
 https://www.bilibili.com/
 https://www.iqiyi.com/
 http://www.zlyk.com/
 */
function clear_all_cartoon_site() {
    for (let key in excluded_cartoon_sites) {
        chrome.tabs.query({url: "*://" + excluded_cartoon_sites[key] + "/" + '*'}, function(tabs) {
            for (let index in tabs) {
                remove_tab(tabs[index]);
            }
        });
    }
}
